package com.zysc.processflow.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zysc.processflow.common.base.PageResult;
import com.zysc.processflow.common.util.StringUtils;
import com.zysc.processflow.entity.*;
import com.zysc.processflow.mapper.*;
import com.zysc.processflow.pojo.SpuBo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import com.baomidou.mybatisplus.core.metadata.IPage;
/**
 * @Author: Mr.Liuyijiang
 * @Description:
 * @Date Created in 2022-06-09 10:11
 * @Modified By:
 */
@Service
public class GoodsService {

    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private SpuDetailMapeer spuDetailMapeer;
    @Autowired
    private BrandMapper brandMapper;
    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private StockMapper stockMapper;


    @Autowired
    private CategoryService categoryService;


    /**
     * 根据条件分页查询spu
     * @param key
     * @param saleable
     * @return
     */
    public List<SpuBo> querySpuByPage(IPage<Spu> spupage,String key, Boolean saleable) {

        LambdaQueryWrapper<Spu> spuQw = new LambdaQueryWrapper<>();
        spuQw.eq(saleable !=null,Spu::getSaleable,saleable)
                .like(!StringUtils.isNull(key),Spu::getTitle,key);
        List<Spu> spus = spuMapper.selectPage(spupage,spuQw).getRecords();

        //将spu转化成spubo集合
        List<SpuBo> spuBos = spus.stream().map(spu -> {
            SpuBo spuBo = new SpuBo();
            BeanUtils.copyProperties(spu, spuBo);
            //cname,bname
            //查询品牌名称

            Brand brand = this.brandMapper.selectById(spuBo.getBrandId());
            spuBo.setBname(brand.getName());
            //查询分类名称
            List<String> cnames = this.categoryService.queryNamesByIds(Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3()));
            spuBo.setCname(String.join("-",cnames));
            return spuBo;
        }).collect(Collectors.toList());

        //返回Result<SpuBo>
        return spuBos;
    }

    /**
     * 新增商品
     * @param spuBo
     */
    @Transactional
    public void saveGoods(SpuBo spuBo) {
        //新增哪几张表？
        spuBo.setSaleable(true);
        spuBo.setValid(true);
        spuBo.setCreateTime(new Date());
        spuBo.setLastUpdateTime(spuBo.getCreateTime());
        //先新增spu
        if(spuBo.getId()!=null){
            this.spuMapper.updateById(spuBo);
        }else {
            this.spuMapper.insert(spuBo);
        }


        //新增spuDetail
        SpuDetail spuDetail = spuBo.getSpuDetail();
        spuDetail.setSpuId(spuBo.getId());
        this.spuDetailMapeer.deleteSpuDetailBySpuId(spuBo.getId());
        if(spuDetail.getId()!=null){
            this.spuDetailMapeer.updateById(spuDetail);
        }else {
            this.spuDetailMapeer.insert(spuDetail);
        }
        saveSkuAndStock(spuBo);

    }

    //公共方法保存sku和stock
    private void saveSkuAndStock(SpuBo spuBo) {
        //新增sku
        spuBo.getSkus().forEach(sku -> {
            //新增stock
            sku.setId(null);
            sku.setSpuId(spuBo.getId());
            sku.setCreateTime(new Date());
            sku.setLastUpdateTime(sku.getCreateTime());
            this.skuMapper.insert(sku);
            //新增stock
            Stock stock = new Stock();
            stock.setSkuId(sku.getId());
            stock.setStock(sku.getStock());
            this.stockMapper.insert(stock);
        });
    }

    /**
     * 根据spuId查询spuDetail
     * @param spuId
     * @return
     */
    public SpuDetail querySpuDetailBySpuId(Long spuId) {
        LambdaQueryWrapper<SpuDetail> spuDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
        spuDetailLambdaQueryWrapper.eq(SpuDetail::getSpuId,spuId);
        SpuDetail spuDetail = this.spuDetailMapeer.selectOne(spuDetailLambdaQueryWrapper);
        return spuDetail;
    }


    /**
     * 根据spuId查询spu的集合
     * @param id
     * @return
     */
    public List<Sku> querySkusBySpuId(Long id) {

        LambdaQueryWrapper<Sku> spuDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
        spuDetailLambdaQueryWrapper.eq(Sku::getSpuId,id);

        List<Sku> skus = this.skuMapper.selectList(spuDetailLambdaQueryWrapper);
        skus.forEach(sku -> {
            LambdaQueryWrapper<Stock> stockLambdaQueryWrapper = new LambdaQueryWrapper<>();
            stockLambdaQueryWrapper.eq(Stock::getSkuId,sku.getId());
            Stock stock = this.stockMapper.selectOne(stockLambdaQueryWrapper);
            sku.setStock(stock.getStock());
        });

        return skus;
    }

    /**
     * 修改商品
     * @param spuBo
     */
    @Transactional
    public void updateGoods(SpuBo spuBo) {
        //根据spu的id查询要删除的sku

        LambdaQueryWrapper<Sku> skuLambdaQueryWrapper = new LambdaQueryWrapper<>();
        skuLambdaQueryWrapper.eq(Sku::getSpuId,spuBo.getId());
        List<Sku> skus = this.skuMapper.selectList(skuLambdaQueryWrapper);
        //删除stock表
        LambdaQueryWrapper<Stock> stockLambdaQueryWrapper = new LambdaQueryWrapper<>();
        stockLambdaQueryWrapper.in(Stock::getSkuId,skus.stream().map(item->item.getId()));
        this.stockMapper.delete(stockLambdaQueryWrapper);
        //删除sku
        Sku sku = new Sku();
        sku.setSpuId(spuBo.getId());
        this.skuMapper.deleteBatchIds(skus);
        //新增sku
        //新增stock表
        this.saveSkuAndStock(spuBo);
        //更新spu和spudetail
        //有一些字段是不允许随便更新的，防止外界使用postman来更新了创建时间，这些字段在前殿界面是不能修改的，但是不保证用postman来修改
        spuBo.setCreateTime(null);
        spuBo.setLastUpdateTime(new Date());
        spuBo.setValid(null);
        spuBo.setSaleable(null);
        this.spuMapper.updateById(spuBo);
        this.spuDetailMapeer.updateById(spuBo.getSpuDetail());

    }
}
